<template>
    <div class="flex-container" :style="{ height: clientHeight + 'px' }">
        <div class="title">Word转PDF</div>
        <el-upload
            ref="upload"
            drag
            :limit="1"
            accept=".docx"
            action="-"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="uploadFile"
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-button type="primary" @click="handleBack" size="medium" round style="margin-top: 25px">返回主页</el-button>
    </div>
</template>

<script>
import axios from 'axios'
import saveAs from 'file-saver'
export default {
    data() {
        return {
            clientHeight: document.documentElement.clientHeight || document.body.clientHeight
        }
    },
    methods: {
        beforeUpload(file) {
            this.$refs.upload.clearFiles()
            let pattern = /.(docx)$/g
            if (!pattern.test(file.name)) {
                this.$message.error('只能上传docx文件')
                return false
            }
            return true
        },
        uploadFile(data) {
            let load = this.$loading({
                lock: true,
                text: '正在导出...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            let filename = data.file.name.split('.')[0]
            let params = new FormData()
            params.append('file', data.file)
            params.append('sourceFormat', 'docx')
            params.append('targetFormat', 'pdf')
            axios.post('https://ys-8080.jcaiwu.com/auth/convert', params, { responseType: 'blob' }).then(res => {
                let content = res.data
                let blob = new Blob([content])
                saveAs(blob, filename + '.pdf')
                load.close()
            })
        },
        handleBack() {
            this.$router.replace('/')
        }
    }
}
</script>

<style scoped>
.flex-container {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}
.el-button--primary {
    background-color: #505587;
    border-color: #505587;
}
.el-upload-dragger .el-upload__text em {
    color: #505587;
}
.title {
    font-size: 24px;
    line-height: 34px;
    color: #33333b;
    font-weight: 600;
    margin-bottom: 25px;
}
</style>
